<template>
  <div class="UserManagementList">
    <el-card class="searchBox">
      <div class="one">
        <el-input placeholder="请输入活动名称" v-model="name">
          <template slot="prepend">活动名称</template>
        </el-input>
        <el-input placeholder="请输入活动ID" v-model="id">
          <template slot="prepend">活动ID</template>
        </el-input>

        <div class="displayPage">
          <p class="p">活动对象</p>
          <el-select
            v-model="sexInput"
            slot="prepend"
            placeholder="请选择活动对象"
          >
            <el-option label="注册用户" value="1"></el-option>
            <el-option label="认证用户" value="2"></el-option>
            <el-option label="工会认证用户" value="3"></el-option>
            <el-option label="平台合作用户" value="4"></el-option>
          </el-select>
        </div>

        <div class="displayPage">
          <p class="p">VIP活动</p>
          <el-select v-model="vipObj" slot="prepend" placeholder="是否为VIP">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </div>

        <el-button
          class="btn"
          @click="activitymanagementListBtn"
          style="width: 100px"
          >查找搜索</el-button
        >
        <el-button class="btn" @click="add" style="width: 100px"
          >新增活动</el-button
        >
      </div>

      <el-tabs @tab-click="handleClick" type="border-card" v-model="activeName">
        <el-tab-pane label="已开启" name="1">
          <el-table :data="tableData" v-loading="loading" style="width: 100%">
            <el-table-column prop="id" label="活动ID"> </el-table-column>
            <el-table-column prop="title" label="活动名称"> </el-table-column>
            <el-table-column prop="imageUrl" label="活动图片">
              <template slot-scope="scope">
                <img :src="scope.row.imageUrl" preview alt="" class="img" />
              </template>
            </el-table-column>
            <el-table-column prop="targetUrl" label="跳转链接">
            </el-table-column>
            <el-table-column label="活动对象">
              <template slot-scope="scope">
                <span>{{ scope.row.identity }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="展示顺序">
              <template slot-scope="scope">
                <el-input
                  style="width: 100px"
                  placeholder=""
                  v-model="scope.row.sort"
                  size="mini"
                >
                </el-input>
                <el-button size="mini" @click="submitSort(scope.row)"
                  >确认</el-button
                >
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="240px">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="stopBtn(scope.row)"
                  >停止</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  @click="openEditBtn(scope.row)"
                  >编辑</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="page"
            :limit.sync="pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
        <el-tab-pane label="未开启" name="0">
          <el-table :data="tableData" v-loading="loading" style="width: 100%">
            <el-table-column prop="id" label="活动ID"> </el-table-column>
            <el-table-column prop="title" label="活动名称"> </el-table-column>
            <el-table-column prop="imageUrl" label="活动图片">
              <template slot-scope="scope">
                <img :src="scope.row.imageUrl" preview alt="" class="img" />
              </template>
            </el-table-column>
            <el-table-column prop="targetUrl" label="跳转链接">
            </el-table-column>
            <el-table-column label="活动对象">
              <template slot-scope="scope">
                {{ scope.row.identity }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleDelete(scope.row)"
                  type="danger"
                  >删除</el-button
                >
                <el-button
                  size="mini"
                  @click="openEditBtn(scope.row)"
                  type="primary"
                  >编辑</el-button
                >
                <!-- <el-button
                size="mini"
                @click="openingActivitiesBtn(scope.row)"
                type="success"
                >开启</el-button
              > -->
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="page"
            :limit.sync="pageSize"
            @pagination="getList"
          />
        </el-tab-pane>
      </el-tabs>

      <!-- 新增活动 -->
      <el-dialog :title="activity" :visible.sync="dialogFormVisible" top="2vh">
        <el-form :model="form" :rules="rules">
          <el-form-item label="活动图片" :required="true">
            <el-upload
              class="avatar-uploader"
              :http-request="upLoad"
              :on-preview="handlePictureCardPreview"
              :on-success="handleAvatarSuccess"
              :show-file-list="false"
              action
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="dialogImageUrl"
                :src="dialogImageUrl"
                class="avatar"
                style="width: 200px; height: 80px; border-radius: 4px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="活动名称" :required="true">
            <el-input v-model="form.title" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="活动链接" :required="true">
            <el-input
              v-model="form.targetUrl"
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
          <el-form-item label="活动对象" :required="true">
            <el-checkbox-group v-model="form.activeObj">
              <el-checkbox label="1">注册用户</el-checkbox>
              <el-checkbox label="2">认证用户</el-checkbox>
              <el-checkbox label="3">公会认证用户</el-checkbox>
              <el-checkbox label="4">合作平台用户</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="显示顺序" :required="true">
            <el-input placeholder="请输入显示顺序" v-model="form.sort">
            </el-input>
          </el-form-item>
          <el-form-item label="是否为VIP" :required="true">
            <el-radio-group v-model="form.isVip">
              <el-radio label="1">VIP用户</el-radio>
              <el-radio label="0">非VIP用户</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="开启活动" :required="true">
            <el-radio-group v-model="form.isOpen">
              <el-radio label="1">开启</el-radio>
              <el-radio label="0">暂不开启</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            v-if="activity == '编辑活动'"
            type="primary"
            @click="activitymanagementEditBtn"
            >确 定</el-button
          >
          <el-button
            v-if="activity == '新增活动'"
            type="primary"
            @click="newConfirmationBtn"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  activitymanagementList,
  activitymanagementOpen,
  activitymanagementInfo,
  activitymanagementEdit,
  activitymanagementAdd,
  activitymanagementOrder,
  activitymanagementDel,
} from "@/api/operationManagement";
import Pagination from "@/components/Pagination"; // 分页
import { client } from "@/utils/oss.js";
import { ossToken } from "@/api/NotificationManagement";

export default {
  components: { Pagination },
  inject: ["reload"],
  data() {
    let isTrueUrl = (rule, value, callback) => {
      let reg =
        /(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的链接"));
      } else {
        callback();
      }
    };
    return {
      rules: {
        targetUrl: [
          { required: true, message: "请输入链接地址", trigger: "blur" },
          { validator: isTrueUrl, trigger: "blur" },
        ],
      },
      sexInput: "", //活动对象选择
      activeName: "1", //选选项卡表示
      vipObj: "", //是否为vip用户
      name: "", //活动名称
      id: "", //活动ID
      sex: "", //活动对象
      sortInput: "", //排序修改input

      dialogFormVisible: false,
      dialogFormVisibleA: false,

      //弹框
      idDialog: "",
      imageUrl: "",
      dialogImageUrl: "",

      //dialog表单
      form: {
        title: "", //活动名称
        targetUrl: "", //活动链接
        activeObj: [], //活动对象
        sort: "", //显示顺序
        isVip: "", //是否为vip
        isOpen: "", // 活动开启状态
      },

      tableData: [],
      loading: true,
      // tableDataA: [],
      total: 0,
      page: 1, //页码
      pageSize: 10, //每页条数
      totalA: 0,
      pageA: 1,
      pageSizeA: 10,
      activity: "新增活动",
    };
  },
  methods: {
    //活动管理列表
    activitymanagementList() {
      this.loading = true;
      activitymanagementList({
        page: this.page,
        pageSize: this.pageSize,
        name: this.name,
        id: this.id,
        index: this.activeName, //默认 1.已开启 0.未开启
        identity: this.sexInput,
        is_vip: this.vipObj,
      }).then((res) => {
        if (res.code == 0) {
          this.tableData = res.data.list;
          this.total = res.data.total;
          this.loading = false;
        }
      });
    },
    // 选项卡
    handleClick() {
      this.activitymanagementList();
    },
    //分页
    getList() {
      this.activitymanagementList();
    },
    //搜索查询
    activitymanagementListBtn() {
      this.activitymanagementList();
    },

    //停止按钮
    stopBtn(row) {
      this.$confirm("此操作将停止该活动, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          activitymanagementOpen({
            id: row.id,
            open: 0, //是否开启活动 0是未开启  1是已开启
          }).then((res) => {
            if (res.code == 0) {
              this.$message({
                message: "操作停止成功",
                type: "success",
              });
              this.reload();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消停止操作",
          });
        });
    },
    //开启编辑按钮
    openEditBtn(row) {
      this.dialogFormVisible = true;
      this.activity = "编辑活动";
      activitymanagementInfo({
        id: row.id,
      }).then((res) => {
        if (res.code == 0) {
          this.form.title = res.data.title;
          this.form.targetUrl = res.data.targetUrl;
          this.form.sort = res.data.sort;
          this.form.isOpen = res.data.isOpen;
          this.dialogImageUrl = res.data.imageUrl;
          this.imageUrl = res.data.imageUrl;
          this.idDialog = res.data.id;
          this.form.isVip = res.data.isVip;
          this.form.activeObj = res.data.identity.split(",");
          // console.log(res, "data");
        }
      });
    },
    //编辑确定按钮
    activitymanagementEditBtn() {
      activitymanagementEdit({
        id: this.idDialog,
        imgUrl: this.imageUrl, //图片
        activityLinks: this.form.targetUrl, //活动链接
        openingActivities: this.form.isOpen, //是否开启活动
        title: this.form.title, //活动标题
        displayOrder: this.form.sort, //显示顺序
        identity: this.form.activeObj.join(","), //类型
        is_vip: this.form.isVip, //vip
      }).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: "编辑成功",
            type: "success",
          });
          // this.reload();
          this.getList();
          this.dialogFormVisible = false;
        }
      });
    },
    // 确认改变排序按钮
    submitSort(row) {
      let arr = row.identity.split(",");
      let newArr = arr.map((item) => {
        if (item == "注册用户") {
          return "1";
        }
        if (item == "认证用户") {
          return "2";
        }
        if (item == "工会认证用户") {
          return "3";
        }
        if (item == "平台合作用户") {
          return "4";
        }
      });
      console.log(row);
      activitymanagementEdit({
        id: row.id,
        imgUrl: row.imageUrl, //图片
        activityLinks: row.targetUrl, //活动链接
        openingActivities: row.is_open, //是否开启活动
        title: row.title, //活动标题
        displayOrder: row.sort, //显示顺序
        identity: newArr.join(","), //类型
        is_vip: row.is_vip, //vip
      }).then((res) => {
        if (res.code == 0) {
          this.$message({
            message: "编辑成功",
            type: "success",
          });
          // this.reload();
          this.getList();
          this.dialogFormVisible = false;
        }
      });
    },
    //已开启添加活动
    add() {
      this.dialogFormVisible = true;
      this.activity = "新增活动";
    },
    //新增确认按钮
    newConfirmationBtn() {
      if (
        this.imageUrl &&
        this.form.targetUrl &&
        this.form.isOpen &&
        this.form.title &&
        this.form.sort &&
        this.form.isVip &&
        this.form.activeObj !== ""
      ) {
        activitymanagementAdd({
          imgUrl: this.imageUrl, //图片
          activityLinks: this.form.targetUrl, //活动链接
          openingActivities: this.form.isOpen, //是否开启活动
          title: this.form.title, //活动标题
          displayOrder: this.form.sort, //显示顺序
          identity: this.form.activeObj.join(","), //类型
          is_vip: this.form.isVip, //vip
        }).then((res) => {
          if (res.code == 0) {
            this.$message({
              message: "新增成功",
              type: "success",
            });
            this.reload();
          }
        });
      } else {
        this.$message({
          message: "请完善必填信息",
          type: "warning",
        });
      }
    },

    // //未开启 编辑
    // handleEdit(row) {
    //   this.dialogFormVisible = true;
    //   this.activity = "编辑活动";
    // },
    //未开启列表 删除
    handleDelete(row) {
      this.$confirm("此操作将删除该活动, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          activitymanagementDel({
            id: row.id,
          }).then((res) => {
            if (res.code == 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              // this.reload();
              this.getList();
              // this.dialogFormVisible
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除操作",
          });
        });
    },
    //未开启列表 开启活动按钮
    // openingActivitiesBtn(row) {
    //   this.$confirm("此操作将开启该活动, 是否继续?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(() => {
    //       activitymanagementOpen({
    //         id: row.id,
    //         open: 1, //是否开启活动 0是未开启  1是已开启
    //       }).then((res) => {
    //         if (res.code == 0) {
    //           this.$message({
    //             message: "操作开启成功",
    //             type: "success",
    //           });
    //           this.reload();
    //         }
    //       });
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: "info",
    //         message: "已取消开启操作",
    //       });
    //     });
    // },

    //覆盖默认的上传行为，自定义上传的实现
    async upLoad(file) {
      await ossToken({
        type: 0,
      }).then((res) => {
        if (res.code == 0) {
          this.dataObj = {
            accessKeyId: res.data.accessKey,
            accessKeySecret: res.data.accessSecret,
            securityToken: res.data.token,
            region: "oss-" + res.data.regionId,
            bucket: res.data.bucket,
          };
        }
      });
      const self = this;
      // try {
      //   let fileNames =
      //     "/img/" +
      //     Math.round(new Date() / 1000) +
      //     "." +
      //     file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      //   this.imageUrl = fileNames;
      //   //fileNames上传文件的名称
      //   //file.file上传文件的内容
      //   let cli = client(this.dataObj);
      //   let result = cli.multipartUpload(fileNames, file);
      //   self.$message({
      //     message: "上传成功",
      //     type: "success",
      //   });
      // } catch (e) {
      //   self.$message.error("上传失败");
      // }

      let files = file.file,
        point = files.name.lastIndexOf("."),
        suffix = files.name.substr(point),
        fileName = files.name.substr(0, point),
        date = Date.parse(new Date()),
        // fileNames = "/img/" + file.file.name;
        fileNames =
          "/img/" +
          Math.round(new Date() / 1000) +
          "." +
          file.file.name.substring(file.file.name.lastIndexOf(".") + 1);
      // console.log(file.file.name.substring(file.file.name.lastIndexOf(".")+1));
      this.imageUrl = fileNames;
      //fileNames上传文件的名称
      //file.file上传文件的内容
      client(this.dataObj)
        .multipartUpload(fileNames, file.file)
        .then((result) => {
          //下面是如果对返回结果再进行处理，根据项目需要
          self.$message({
            message: "上传成功",
            type: "success",
          });
        })
        .catch((err) => {
          self.$message.error("上传失败");
        });
    },
    handleAvatarSuccess(res, file) {
      this.dialogImageUrl = URL.createObjectURL(file.raw);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      return isJPG;
    },
  },
  created() {
    this.activitymanagementList();
  },
};
</script>

<style lang="less" scoped>
.UserManagementList {
  margin: 30px;
  height: 100%;
  .searchBox {
    .one {
      display: flex;
      margin-bottom: 20px;
      .el-input {
        width: 240px;
        margin-right: 20px;
      }
      .el-button {
        margin-left: 20px;
        height: 40px;
      }

      .displayPage {
        display: flex;
        .el-select {
          width: 160px;
          margin-right: 20px;
          .el-input {
            width: 160px;
          }
        }
        .p {
          border: 1px solid #dcdfe6;
          border-right: 0px;
          height: 40px;
          line-height: 20px;
          margin: 0px;
          background: #f5f7fa;
          color: #909399;
          font-size: 14px;
          padding: 10px;
          border-radius: 4px 0px 0px 4px;
        }
      }
    }

    .address {
      width: 120px;
    }
    .btn {
      margin-left: 4px;
      height: 40px;
    }

    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 80px;
      line-height: 80px;
      text-align: center;
      border: 1px dashed #d9d9d9;
    }
    .avatar {
      width: 200px;
      height: 80px;
      display: block;
    }
  }

  .p {
    display: flex;
    p {
      width: 100px;
      height: 40px;
      line-height: 40px;
      text-align: center;
    }
  }
  .active {
    background-color: #0079fe;
    color: #fff;
    border-radius: 10px;
  }
  .img {
    width: 140px;
    height: 70px;
    border-radius: 4px;
  }
}
</style>